package com.duleme.servlet;

import com.duleme.common.EncodeUtils;
import com.duleme.common.JsonUtils;
import com.duleme.dao.BookDao;
import com.duleme.entity.Book;
import com.duleme.entity.ShoppingCart;
import com.duleme.entity.User;
import com.duleme.service.CartService;
import com.duleme.service.impl.CartServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "UserCartServlet",urlPatterns = "/data/cart")
public class UserCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EncodeUtils.setEncoding(request,response);
        Integer bookId = Integer.valueOf(request.getParameter("bookID"));
        Integer count = Integer.valueOf(request.getParameter("count"));
        Book book = new BookDao().findBookByBookId(bookId);
        User user = (User) request.getSession().getAttribute("user");
        CartService cartService = new CartServiceImpl();
        PrintWriter writer = response.getWriter();
        if (cartService.addBook2Cart(user.getUserId(),book,count)){
            String json = JsonUtils.result2Json("1");
            System.out.println(json);
            writer.write(json);
            writer.close();
        }else {
            String json = JsonUtils.result2Json("2");
            System.out.println(json);
            writer.write(json);
            writer.close();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EncodeUtils.setEncoding(request,response);
        CartService cartService = new CartServiceImpl();
        User user = (User) request.getSession().getAttribute("user");
        //User user = new User();
        //user.setUserId(100020);
        ShoppingCart cart = cartService.getBookCart(user.getUserId());
        String cartJson = JsonUtils.toJson(cart);
        String json = JsonUtils.result2Json("1","info",cartJson);
        System.out.println(cartJson);
        response.getWriter().write(json);
    }
}
